//
//  YZMainTabBarController.m
//  VET
//
//  Created by Lam BG on 2018/6/25.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZMainTabBarController.h"
#import "YZMainNavigationController.h"

#import "YZWorkbenchVC.h"
#import "YZIMVC.h"
#import "YZCommunityVC.h"
#import "YZCommunityHomeVC.h"
#import "YZPersonalCenterVC.h"

#import "YZMainTabBar.h"
#import "SVProgressHUD.h"
#import "TBCityIconFont.h"
#include "YZStatementHeader.h"

#import "UIImage+Category.h"
#import "YZChatMainVC.h"
#import "YZFasterPopView.h"
#import "YZFasterPopItem.h"
#import "YZRouter+AutoVC.h"
#import "YZPublishCommunityVC.h"
#import "YZAudioRecordVC.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIViewController+YZImagePicker.h"
#import "YZNetworkConfig.h"
#import "YZPublishWorkNoteManage.h"
#import "YZCameraVC.h"
#import "YZVideoVC.h"
#import "TZImagePickerController.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
@interface YZMainTabBarController ()<YZMediaProtocol>
@property (nonatomic, strong) YZFasterPopView *popView;
@end

@implementation YZMainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupControllers];
    [self setupCenterTabBar];
}

- (void)dealloc {
    
    NSLog(@"--- %@ dealloc ---", NSStringFromClass([self class]));
}

#pragma mark - private function

- (void)setupControllers {
    
    // 工作台
    YZWorkbenchVC *wbVC = [[YZWorkbenchVC alloc] initWithNibName:@"YZWorkbenchVC" bundle:nil];
    [self configViewController:wbVC title:@"工作台" imageCode:@"\ue639"];
    
    // 消息
    YZChatMainVC *chatVC = [[YZChatMainVC alloc] init];
    [self configViewController:chatVC title:@"影信" imageCode:@"\ue636"];
    
    // 圈子
    YZCommunityHomeVC *cmVC = [[YZCommunityHomeVC alloc] initWithUrl:[NSString stringWithFormat:@"%@/#/circle",[YZNetworkConfig getUrlCurrentDomain]] registerFunctions:nil];
    [self configViewController:cmVC title:@"圈子" imageCode:@"\ue638"];
    
    // 个人中心
    UIStoryboard *personalStoryboard = [UIStoryboard storyboardWithName:@"personalCenter" bundle:nil];
    YZPersonalCenterVC *pcVC = [personalStoryboard instantiateViewControllerWithIdentifier:@"YZPersonalCenterVC"];
    [self configViewController:pcVC title:@"我" imageCode:@"\ue637"];
}

- (void)configViewController:(UIViewController*)rootVC title:(NSString*)title imageCode:(NSString*)iconfont {
    
    // 图案
    UIImage *img = [[UIImage iconWithInfo:TBCityIconInfoMake(iconfont, 24, yzGrayColor)] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    UIImage *selectImg = [[UIImage iconWithInfo:TBCityIconInfoMake(iconfont, 24, yzGreenColor)] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    rootVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:img selectedImage:selectImg];
    
    // 可以调整 tabBarItem 图片大小
//    rootVC.tabBarItem.imageInsets = UIEdgeInsetsMake(0, -10, -2, -10);
    // tabBarItem 字体颜色 大小
    float fontSize = 12;
    [rootVC.tabBarItem setTitleTextAttributes:@{ NSForegroundColorAttributeName : yzGreenColor,
                                                 NSFontAttributeName : [UIFont systemFontOfSize:fontSize]
                                                 }forState:UIControlStateSelected];
    [rootVC.tabBarItem setTitleTextAttributes:@{ NSForegroundColorAttributeName : yzGrayColor,
                                                 NSFontAttributeName : [UIFont systemFontOfSize:fontSize] }forState:UIControlStateNormal];
    
    // 导航及其 root vc
    YZMainNavigationController *nav = [[YZMainNavigationController alloc] initWithRootViewController:rootVC];
    rootVC.title = title;
    [self addChildViewController:nav];
}

- (void)setupCenterTabBar {
    
    // tabbar 背景色
    [[UITabBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
    // 设置分割线
    [[UITabBar appearance] setShadowImage:[UIImage imageWithColor:kColorWithHex(0xD9D9D9)]];
    
    // 设置自定义的tabbar
    YZMainTabBar *tb = [[YZMainTabBar alloc] init];
    [self setValue:tb forKeyPath:@"tabBar"];
    [tb.centerBtn addTarget:self action:@selector(centerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - action 按钮事件

- (void)centerBtnClick:(UIButton *)btn{
   //添加popview
    YZFasterPopItem *item1  = [[YZFasterPopItem alloc] initWithTitle:@"猪只建档" icon:@"faster_swine"];
    item1.autoHide = YES;
    YZFasterPopItem *item2  = [[YZFasterPopItem alloc] initWithTitle:@"猪群建档" icon:@"faster_herd"];
    item2.autoHide = YES;
    YZFasterPopItem *item3  = [[YZFasterPopItem alloc] initWithTitle:@"语音存档" icon:@"faster_audio"];
    YZFasterPopItem *item4  = [[YZFasterPopItem alloc] initWithTitle:@"拍照存档" icon:@"faster_picture"];
    YZFasterPopItem *item5  = [[YZFasterPopItem alloc] initWithTitle:@"视频存档" icon:@"faster_video"];
    YZFasterPopItem *item6  = [[YZFasterPopItem alloc] initWithTitle:@"发布动态" icon:@"faster_publish"];
    item6.autoHide = YES;
   [YZFasterPopView showToView:self.view withItems:@[item1,item2,item3,item4,item5,item6] andSelectBlock:^(YZFasterPopItem *item) {
        if ([item.title isEqualToString:@"猪只建档"]) {
            [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwine"];
        }else if ([item.title isEqualToString:@"猪群建档"]) {
            [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwinery"];
        }else if ([item.title isEqualToString:@"语音存档"]){
            [self startAudioRecrd];
            
        }else if ([item.title isEqualToString:@"拍照存档"]){
            YZCameraVC *cameraVC = [YZCameraVC new];
            cameraVC.delegate = self;
            [self presentViewController:cameraVC animated:YES completion:nil];
        }else if ([item.title isEqualToString:@"视频存档"]){
            YZVideoVC *videoVC = [YZVideoVC new];
            videoVC.delegate = self;
            [self presentViewController:videoVC animated:YES completion:nil];
        }else if ([item.title isEqualToString:@"发布动态"]){
            YZPublishCommunityVC *publishVC = [[YZPublishCommunityVC alloc] init];
            [self.selectedViewController pushViewController:publishVC animated:YES];
        }
    }];
}

#pragma mark -- YZMediaProtocol

- (void)getCurrentVideoAssert:(PHAsset *)assert andUrl:(NSURL *)url  andCurrentOrientation:(AVCaptureVideoOrientation)orientation
{
    if (!assert) return;
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    //[tzImagePickerVc showProgressHUD];
    [[TZImageManager manager] saveVideoWithUrl:url location:nil completion:^(NSError *error) {
        if (!error) {
            [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:NO needFetchAssets:NO completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:NO completion:^(NSArray<TZAssetModel *> *models) {
                   // [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    //视频保存到本地
                    [self getVideoOutputPathWithAsset:assetModel.asset andCurrentOrientation:orientation];
                }];
            }];
        } else {
            [tzImagePickerVc hideProgressHUD];
        }
    }];
}

- (void)getCurrentPhotoAssert:(PHAsset *)assert
{
    if (!assert) return;
    @weakify(self)
    [[TZImageManager manager] getOriginalPhotoWithAsset:assert completion:^(UIImage *photo, NSDictionary *info) {
        if (photo) {
            [[YZPublishWorkNoteManage shareManager] publishWorkNote:nil mediaPath:nil selectedPhotos:@[photo] mediaParams:nil completion:^{
                
                YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
                [customView setupUIWithTitle:nil message:@"当前图片已保存在笔记中" confirmTitle:@"确定" cancelTitle:@"继续拍照" confirmHandler:^{
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                    
                } cancelHandler:^{
                    [self.YZ_popupController dismiss];
                    YZCameraVC *cameraVC = [YZCameraVC new];
                    cameraVC.delegate = self;
                    [self presentViewController:cameraVC animated:YES completion:nil];
                }];
                [self.YZ_popupController presentContentView:customView];
            }];
        }
    }];
}

- (void)getVideoOutputPathWithAsset:(id)asset andCurrentOrientation:(AVCaptureVideoOrientation)orientation{
    @weakify(self)
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPreset640x480 success:^(NSString *outputPath) {
        NSString *mediaOrientation = @"top";
        switch (orientation) {
            case AVCaptureVideoOrientationPortrait:
                mediaOrientation = @"top";
                break;
            case AVCaptureVideoOrientationPortraitUpsideDown:
                mediaOrientation = @"bottom";
                break;
            case AVCaptureVideoOrientationLandscapeRight:
                mediaOrientation = @"right";
                break;
            case AVCaptureVideoOrientationLandscapeLeft:
                mediaOrientation = @"left";
                break;
        }
        [[YZPublishWorkNoteManage shareManager] publishWorkNote:nil mediaPath:outputPath selectedPhotos:nil mediaParams:@{@"mediaType":@"video/mp4",@"mediaOrientation":mediaOrientation} completion:^{
            YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
            [customView setupUIWithTitle:nil message:@"当前视频已保存在笔记中" confirmTitle:@"确定" cancelTitle:@"继续拍摄" confirmHandler:^{
                @strongify(self)
                [self.YZ_popupController dismiss];
                
            } cancelHandler:^{
                [self.YZ_popupController dismiss];
                YZVideoVC *videoVC = [YZVideoVC new];
                videoVC.delegate = self;
                [self presentViewController:videoVC animated:YES completion:nil];
            }];
            [self.YZ_popupController presentContentView:customView];
        }];
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
}

- (void)startAudioRecrd{
    YZAudioRecordVC  *recordVC = [[YZAudioRecordVC alloc] init];
    recordVC.recordSuccessBlock = ^(NSString *recordPath, NSInteger timeInterval) {
        YZPublishWorkNoteManage *publishManage = [YZPublishWorkNoteManage shareManager];
        @weakify(self)
        [publishManage publishWorkNote:nil mediaPath:recordPath selectedPhotos:nil mediaParams:@{@"mediaType":@"audio/aac", @"mediaTime":@(timeInterval)} completion:^{
            YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
            [customView setupUIWithTitle:nil message:@"当前语音已保存在笔记中" confirmTitle:@"确定" cancelTitle:@"继续录音" confirmHandler:^{
                @strongify(self)
                [self.YZ_popupController dismiss];
                
            } cancelHandler:^{
                @strongify(self)
                [self.YZ_popupController dismiss];
                [self startAudioRecrd];
            }];
            [self.YZ_popupController presentContentView:customView];
        }];
    };
    [self presentViewController:recordVC animated:YES completion:nil];
}
@end
